package com.doeis.uwork.servce;

import java.awt.image.BufferedImage;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.doeis.common.utils.StringUtils;
import com.doeis.log.QueueManager;
import com.doeis.minaserver.NettyServer;
import com.doeis.minaserver.container.BasicModule;
import com.doeis.minaserver.dao.User;
import com.doeis.minaserver.dao.UserDao;
import com.doeis.minaserver.packet.InfoPacket;
import com.doeis.minaserver.packet.ServerPacketFactory;
import com.doeis.minaserver.session.ClientConnection;
import com.doeis.uwork.bean.ComparatorRelation;
import com.doeis.uwork.bean.ItemAssist;
import com.doeis.uwork.bean.ItemAttrs;
import com.doeis.uwork.common.Constant;
import com.doeis.uwork.common.ImageUtils;
import com.doeis.uwork.common.PacketUtil;
import com.doeis.uwork.dao.GroupMsgMongoDao;
import com.doeis.uwork.dao.ItemDao;
import com.doeis.uwork.dao.OffPacketMongoDao;
import com.doeis.uwork.dao.ShareDao;
import com.doeis.uwork.dao.TemplateDao;
import com.doeis.uwork.entity.Item;
import com.doeis.uwork.entity.PictureInfo;
import com.doeis.uwork.entity.Share;
import com.doeis.uwork.entity.Template;
import com.doeis.uwork.entity.mongo.GroupMsg;
import com.doeis.uwork.entity.mongo.MessageUser;
import com.doeis.uwork.entity.mongo.OffPacket;
import com.doeis.uwork.entity.mongo.PictureInfoMongo;
import com.doeis.uwork.packet.GroupMsgPacket;
import com.doeis.uwork.packet.PrivateMsgPacket;
import com.mongodb.BasicDBObject;
import com.voland.core.ServiceException;
import com.voland.core.db.DBManager;
import com.voland.core.db.DaoException;
import com.voland.core.utils.DateUtils;
import com.voland.core.utils.IDGenerator;

public class GroupMsgService extends BasicModule {

	private static final Logger log = Logger.getLogger(GroupMsgService.class);
	
	private UserDao userDao;
	private ItemDao itemDao;
	private ShareDao shareDao;
	private GroupMsgMongoDao groupMsgMongoDao;
	private OffPacketMongoDao offPacketMongoDao;
	private PictureInfoMongo pictureInfoMongo;
	private TemplateDao templateDao;
	
	
	public GroupMsgService() {
		super(" group Message Service ");
	}
	
	public GroupMsgService(String moduleName) {
		super(moduleName);
	}

	@Override
	public void initialize(NettyServer server) {
		this.server = server;
		
		userDao = server.getUserDao();
		offPacketMongoDao = server.getOffPacketMongoDao();
		
		itemDao = server.getItemDao();
		shareDao = server.getShareDao();
		groupMsgMongoDao = server.getGroupMsgMongoDao();
		pictureInfoMongo = server.getPictureInfoMongo();
		templateDao = server.getTemplateDao();
		
	}
	
	public void acknowledgeReceipt(ClientConnection clientConn, GroupMsgPacket packet){
		try{
			//收到确认消息
			if(StringUtils.isBlank(packet.getBody())){
				return ;
			}
			
			GroupMsg groupMsg = packet.decoder(GroupMsg.class);
			if(groupMsg!=null){
				User user = userDao.findUserByid(groupMsg.getUserId());
				if(user!=null){
					BasicDBObject query = new BasicDBObject("userId", groupMsg.getUserId());
					query.put("bodyid", groupMsg.getId());
					offPacketMongoDao.delete(user.getSwitchboard_id(), OffPacket.class, query);
				}
			}
			GroupMsgPacket info = ServerPacketFactory.createGroupMessagePacket( packet.getFrom() );
			
			info.setBody("{\"id\":\""+groupMsg.getId()+"\"}");
			info.setCmd(GroupMsgPacket.CONFIRM_MSG_ADD_OTHER_RE);
			info.setNotifyType(GroupMsgPacket.NT_RE_MSG_OK);
			clientConn.deliver(info);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			DBManager.closeBindConnection(DBManager.getDefaultDataSourceName(Boolean.TRUE.booleanValue()));
		}
		
	}
	/**
	 * 添加信息
	 * @param clientConn
	 * @param packet
	 */
	/**
	 * @param clientConn
	 * @param packet
	 * @author wxy 2015年7月25日星期六中国标准时间下午5:40:19
	 */
	public void addMsg(ClientConnection clientConn, GroupMsgPacket packet) {
		GroupMsg groupMsg = packet.decoder(GroupMsg.class);
		try{
			//验证登陆输入的参数
			Map<String, Object> errerInfos = new HashMap<String, Object>();
			if(groupMsg.getFrom()==null){
				errerInfos.put("from", "发送人不能为空");
			}
			if(groupMsg.getSourceType()==null){
				errerInfos.put("sourceType", "共享信息类型不能为空");
			}
			if(groupMsg.getMsceneType()==null){
				errerInfos.put("msceneType", "小场景类型不能为空");
			}
			if(groupMsg.getSourceId()==null){
				errerInfos.put("sourceId", "指数、模板、拼图id不能为空");
			}
			if(groupMsg.getContent()==null){
				errerInfos.put("content", "聊天信息不能为空");
			}
			
			
			User myuser = userDao.findUserByid(groupMsg.getFrom());
			if(!StringUtils.isBlank(groupMsg.getIdentification())){
				//去查找是否已经发送过这条消息
				groupMsg.setUserId(myuser.getId());
				GroupMsg tempMsg = groupMsgMongoDao.findGroupMsg(myuser.getSwitchboard_id(), groupMsg);
				if(tempMsg!=null){
					//如果共享信息类型是指数
					if(Constant.SHARE_TYPE_ITEM.equals(groupMsg.getSourceType())){
						//设置指数的原始ID
						Item item = itemDao.findItemByid(groupMsg.getSourceId());
						if(item!=null){
							tempMsg.setSourceName(item.getItem_name());
						}
					}else if(Constant.SHARE_TYPE_TEMPLATE.equals(groupMsg.getSourceType())){
						Share share = shareDao.findShareByid(groupMsg.getShareid());
						if(share!=null){
							tempMsg.setSourceName(share.getName());
						}
					}
					
					GroupMsgPacket reply = ServerPacketFactory.replyAddGroupMessage(myuser.getId(), JSON.toJSONString(tempMsg) );
					reply.setNotifyType(GroupMsgPacket.NT_RE_MSG_OK);
					clientConn.deliver(reply);
					return ;
				}
			}
			
			
			String msgType = "1";
			if(!StringUtils.isBlank(groupMsg.getMsgType())){
				msgType = groupMsg.getMsgType();
			}
			groupMsg.setMsgType(msgType);
			
			if (errerInfos.size() > 0 ) {				
				sendSystemPacket(clientConn, packet.getFrom(),errerInfos.toString(),GroupMsgPacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PARAM_NULL);
				return ;
			}
			String share_user_id = groupMsg.getFrom() ;
			Share share = shareDao.readByCondition(Share.class, "id=?", groupMsg.getShareid());
			if(share!=null){
				groupMsg.setGroup_avatar(share.getHead_pic());
			}
			
			//如果共享信息类型是指数
			if(Constant.SHARE_TYPE_ITEM.equals(groupMsg.getSourceType())){
				//设置指数的原始ID
				Item item = itemDao.findItemByid(groupMsg.getSourceId());
				
				String text_itemString = null;
				if(Constant.DATA_SOURCE_SHARE.equals(item.getData_source())){
					groupMsg.setSourceId(item.getOriginal_item_id());
					Item original_item = itemDao.findItemByid(item.getOriginal_item_id());
					share_user_id = original_item.getUser_id();
					groupMsg.setSourceName(original_item.getItem_name());
//					fromuser = userDao.findUserByid(original_item.getUser_id());
					text_itemString = original_item.getAttrs();
				}else{
					groupMsg.setSourceName(item.getItem_name());
					text_itemString = item.getAttrs();
				}
				
				if(!StringUtils.isBlank(text_itemString)){
					try {
						ItemAttrs itemAttrs = JSON.parseObject(text_itemString, ItemAttrs.class);
						groupMsg.setTextItem(itemAttrs.isTextItem());
					} catch (Exception e) {
					}
				}
				
			}else if(Constant.SHARE_TYPE_TEMPLATE.equals(groupMsg.getSourceType())){
				if(share!=null){
					Template template = templateDao.readByCondition(Template.class, "id=?", false, share.getSource_id());
					if(template!=null){
						groupMsg.setSkin(template.getSkin());
					}
					groupMsg.setSourceId(share.getSource_id());
					share_user_id = share.getUser_id();
					groupMsg.setSourceName(share.getName());
				}
			}
			//判断是否已经选择接受用户
			if(StringUtils.isBlank(groupMsg.getTo())){
				String to = "";
				User share_user = userDao.findUserByid(share_user_id);
				if(share_user!=null){
					List<User> listUser = getShareUser(groupMsg, share_user, groupMsg.getFrom());
					boolean exitshareuser = false ;
					if(listUser!=null){
						for(User user : listUser){
							to+=user.getId()+",";
							if(user.getId().equals(share_user_id)){
								exitshareuser = true ;
							}
						}
					}
					if(share_user_id.equals(groupMsg.getFrom())){//信息发送者是 （这个定制或者指数的共享者）
						
					}else{
						if(!exitshareuser){
							to+=share_user_id+",";
						}
					}
					groupMsg.setTo(to);
				}
			}
			
			String userid = groupMsg.getFrom();
			GroupMsg groupMsg2 = add(groupMsg);
			groupMsg2.setUserId(userid);
			groupMsg2.setSourceName(groupMsg.getSourceName());
			
			GroupMsgPacket reply = ServerPacketFactory.replyAddGroupMessage(userid, JSON.toJSONString(groupMsg2) );
			reply.setNotifyType(GroupMsgPacket.NT_RE_MSG_OK);
			clientConn.deliver(reply);
			
			//把数据插入导数据库中
			offPacketMongoDao.insert(myuser.getSwitchboard_id(), PacketUtil.cloneOffPacket(reply, myuser.getId(), groupMsg2.getId() ));
			
		}catch(Exception e){
			e.printStackTrace();
			log.error("查询用户", e.getCause());
		}finally{
			DBManager.closeBindConnection(DBManager.getDefaultDataSourceName(Boolean.TRUE.booleanValue()));
		}
	}
	
	/**
	 * 客户端接收到服务器通知消息，再次向服务器发送确认消息
	 * @param clientConn
	 * @param packet
	 */
	public void comfirmAddMsg(ClientConnection clientConn, GroupMsgPacket packet) {
		GroupMsg groupMsg = packet.decoder(GroupMsg.class);
		try{
			User user = userDao.findUserByid(groupMsg.getUserId());
			List<OffPacket> listOffPacket = offPacketMongoDao.findOffPacketBybodyid(user.getSwitchboard_id(), 
					groupMsg.getId(), user.getId() );
			if(listOffPacket!=null || listOffPacket.size() > 0 ){
				for(OffPacket packet2 : listOffPacket ){
					if(GroupMsgPacket.NOTIFY_MSG_ADD == packet2.getCmd() ){
						offPacketMongoDao.delete(user.getSwitchboard_id(), packet2 );
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 废弃了
	 * @deprecated
	 * @param groupMsg
	 * @return
	 * @author wxy 2015年6月12日星期五中国标准时间下午2:59:08
	 */
	private String changeContent(GroupMsg groupMsg){
		String result = groupMsg.getContent();
		if (groupMsg!=null) {
			String msgType = groupMsg.getMsgType();
			if ("2".equals(msgType)) {
				String content = groupMsg.getContent();
				if (content!=null) {
					System.out.println(content);
					content = content.replace("110", "108");
					BufferedImage image = null;
					try {
						image = ImageUtils.getBufferedImage(new URL(content));
					} catch (MalformedURLException e) {
						e.printStackTrace();
					}
					if (image!=null) {
//						BASE64Encoder encoder = new BASE64Encoder();
						int height = ImageUtils.getHeight(image, 100, true);
						image = ImageUtils.resize(100, height, image);
						byte[] data = ImageUtils.imageToBytes(image, "png");
//						result = encoder.encode(data);
//						groupMsg.setBase_64(data);
						System.out.println("length==="+result);
					}
				}
			}
		}
		return result;
	}
	
	/**
	 * @param shareuser 共享人
	 * **/
	private List<User> getShareUser(GroupMsg groupMsg,User shareuser,String file_user_id ) throws DaoException{
		List<User> listUser = new ArrayList<User>();
		Set<String> user_id_set = new HashSet<String>();
		User temp = null;
		Share share = shareDao.findShareByid(groupMsg.getShareid());
		if(share==null){
			return listUser;
		}
		
		
		if(Constant.SHARE_SCOPE_ZHIDING.equals(share.getScope())){//组内指定用户
			for(String mobile : share.getEmails().split(" ")){
				List<User> listTempUser = userDao.findUserByMobile(mobile, shareuser.getSwitchboard_id());
				if(listTempUser==null){
					continue ;
				}
				
				for(User user : listTempUser){
					if(file_user_id.equals(user.getId())){
						continue;
					}
					
					if(!user_id_set.contains(user.getId())){
						temp = new User();
						temp.setId(user.getId());
						temp.setName(user.getName());
						temp.setHead_pic(user.getHead_pic());
						user_id_set.add(user.getId());
						listUser.add(temp);
					}
				}
			}
		}else if(Constant.SHARE_SCOPE_ZHIDING_FANGDO.equals(share.getScope()) ){//组外指定用户
			User user = null;
			for(String mobile : share.getEmails().split(" ")){
				user = userDao.findUserByLogin(mobile.trim());
				
				if(user==null){
					continue;
				}
				
				if(file_user_id.equals(user.getId())){
					continue;
				}
				
				if(!user_id_set.contains(user.getId())){
					temp = new User();
					temp.setId(user.getId());
					temp.setName(user.getName());
					temp.setHead_pic(user.getHead_pic());
					user_id_set.add(user.getId());
					listUser.add(temp);
				}
			}
		}else if(Constant.SHARE_SCOPE_DEP.equals(share.getScope())){//本部门
			List<User> listUsers = userDao.findUserByDepartmentId(shareuser.getDepartment_id(), false);
			if(listUsers!=null){
				for(User user :listUsers ){
					if(file_user_id.equals(user.getId())){
						continue;
					}
					if(!user_id_set.contains(user.getId())){
						temp = new User();
						temp.setId(user.getId());
						temp.setName(user.getName());
						temp.setHead_pic(user.getHead_pic());
						user_id_set.add(user.getId());
						listUser.add(temp);
					}
				}
			}
		}else if(Constant.SHARE_SCOPE_COMPANY.equals(share.getScope())){//本组
			List<User> listUsers = userDao.findUserBySwitchBoard(shareuser.getSwitchboard_id(), false);
			if(listUsers!=null){
				for(User user :listUsers ){
					if(file_user_id.equals(user.getId())){
						continue;
					}
					if(!user_id_set.contains(user.getId())){
						temp = new User();
						temp.setId(user.getId());
						temp.setHead_pic(user.getHead_pic());
						temp.setName(user.getName());
						user_id_set.add(user.getId());
						listUser.add(temp);
					}
				}
			}
		}
		
		
		return listUser;
	}
	
	private GroupMsg add(GroupMsg groupmsg) throws ServiceException{
		try{
			Timestamp time = DateUtils.currentDateTime();
			groupmsg.setCreated_at( time );
			
			User fromUser = userDao.findUserByid(groupmsg.getFrom());
			if(fromUser==null){
				groupmsg.setError("发送到的用户不存在");
				return groupmsg;
			}
			groupmsg.setHead_pic(fromUser.getHead_pic());
			MessageUser messageUser = new MessageUser(); 
			messageUser.setName(fromUser.getName());
			messageUser.setUser_id(fromUser.getId());
			groupmsg.setFromUser(JSON.toJSONString(messageUser));//设置发送者
			
			//对方存入这条消息
			User toUser = null;
			List<User> list_to_user = new ArrayList<User>();
			List<MessageUser> list_to = new ArrayList<MessageUser>();
			for(String toId :groupmsg.getTo().split(",")){
				if(!StringUtils.isBlank(toId)){
					toUser = userDao.findUserByid(toId);
 					if(toUser!=null){
						messageUser = new MessageUser(); 
						messageUser.setName(toUser.getName());
						messageUser.setUser_id(toUser.getId());  
						list_to.add(messageUser);
						list_to_user.add(toUser);
					}
				}
			}
			
			String groupid = IDGenerator.uuid();
			groupmsg.setToUser(JSON.toJSONString(list_to));//设置接受者
			groupmsg.setId(groupid);		
			//给自己存入这条信息
			groupmsg.setUserId(groupmsg.getFrom());
			groupMsgMongoDao.insert(fromUser.getSwitchboard_id(), groupmsg);
			//信息接受者
			//changeContent(groupmsg);
			QueueManager queueManager = NettyServer.getInstance().getT(QueueManager.class);
			for(User user : list_to_user){
				groupmsg.setId( IDGenerator.uuid());		
				groupmsg.setUserId(user.getId());
				groupMsgMongoDao.insert(user.getSwitchboard_id(), groupmsg);
				GroupMsgPacket reply = ServerPacketFactory.createGroupMessagePacket(user.getId());
				reply.setBody(JSON.toJSONString(groupmsg));
				reply.setCmd(GroupMsgPacket.CMD_MSG_ADD_OTHER);
				reply.setNotifyType(GroupMsgPacket.NT_RE_MSG_OK);
				
				if(queueManager!=null){
					queueManager.sendPacket(reply);
				}
				/*ClientConnection clientConnection = clientConnectionManager.getAuthConnection(user.getId());
				if(clientConnection!=null){
					clientConnection.deliver(reply);
				}else{
					//极光推送，只有苹果有
					DoeisJPush.sendNotification(user.getId(), fromUser.getName()+":"+groupmsg.getContent());
				}*/
				//保存到数据库中
//				offPacketMongoDao.insert(user.getSwitchboard_id(), PacketUtil.cloneOffPacket(reply, user.getId(), groupmsg.getId() ));
			}
			groupmsg.setId(groupid);
			return groupmsg;
		}catch(Exception e){
			throw new ServiceException(e);
		}		
	}
	
	
	public static void main(String[] args) {
		GroupMsgPacket packet = new GroupMsgPacket();
		System.err.println(packet.getClass().getName());
	}
	
	/**
	 * 获取列表聊天信息
	 * @param userId 用户ID
	 * @param _start 开始个数
	 * @param _end 结束个数
	 * @param clientConn
	 * @param packet
	 */
	public void listMsg(ClientConnection clientConn, GroupMsgPacket packet) {
		//验证登陆输入的参数
		try{
			GroupMsg groupMsg = packet.decoder(GroupMsg.class);
			//验证登陆输入的参数
			Map<String, Object> errerInfos = new HashMap<String, Object>();
			if(groupMsg.getUserId()==null){
				errerInfos.put("userId", "登陆者不能为空");
			}
			if(groupMsg.getSourceType()==null){
				errerInfos.put("sourceType", "共享信息类型不能为空");
			}
			
			if(groupMsg.getSourceId()==null){
				errerInfos.put("sourceId", "指数、模板、拼图id不能为空");
			}
			
			if(groupMsg.getShareid()==null){
				errerInfos.put("shareid", "共享shareid不能为空");
			}
			if (errerInfos.size() > 0 ) {				
				sendSystemPacket(clientConn, packet.getFrom(),errerInfos.toString(),GroupMsgPacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PARAM_NULL);
				return ;
			}
			String user_id = groupMsg.getUserId();
			
//			User myuser = userDao.findUserByid(groupMsg.getUserId())
			User myuser = userDao.readByCondition(User.class, "id=?", groupMsg.getUserId() );
			if(myuser==null){
				sendSystemPacket(clientConn, packet.getFrom(),"没有找到用户",GroupMsgPacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PARAM_NULL);
				return ;
			}
			
			//如果共享信息类型是指数
			if(Constant.SHARE_TYPE_ITEM.equals(groupMsg.getSourceType())){
				//设置指数的原始ID
				Item item = itemDao.findItemByid(groupMsg.getSourceId());
				if(item!=null){
					if(Constant.DATA_SOURCE_SHARE.equals(item.getData_source())){
						groupMsg.setSourceId(item.getOriginal_item_id());
					}
				}
			}else if(Constant.SHARE_TYPE_TEMPLATE.equals(groupMsg.getSourceType())){
				Share share = shareDao.findShareByid(groupMsg.getShareid());
				if( share!=null ){
					groupMsg.setSourceId(share.getSource_id());
				}
			}
			Integer start = groupMsg.getPage();
			Integer count = 10;
			if(start==null){
				start = 0;
			}
			
			List<GroupMsg> msgs = groupMsgMongoDao.findGroupMsg(myuser.getSwitchboard_id(), start,count,  groupMsg);
			if(msgs!=null){//处理聊天信息的头像连接
				String msgType = "1";
				for( GroupMsg temp : msgs){
					if(!StringUtils.isBlank(temp.getMsgType())){
						msgType = temp.getMsgType();
					}else {
						msgType = "1";
					}
					temp.setMsgType(msgType);
					MessageUser messageUser = JSON.parseObject(temp.getFromUser(), MessageUser.class);
					if( user_id.equals(messageUser.getUser_id()) ){
						temp.setHead_pic(myuser.getHead_pic());
					}else{
						User user = userDao.readByCondition(User.class, "id=?", messageUser.getUser_id());
						if(user!=null){
							temp.setHead_pic(user.getHead_pic());
						}
					}
					
					//处理qq中@的特殊字符 //"@Tan  duang了之后打开应用了吗？ 打开之后点进去看了吗？ 看了就算是已读了。有小红点才不正常吧"
//					if(temp.getContent()!=null ){
//						String text = temp.getContent();
////						text = text.replace('', ' ');
////						text = text.replace('', ' ');
////						temp.setContent(text);
//					}
					//因为太长，客户端没有用，节约流量
					temp.setToUser(null);
					//changeContent(temp);
					
					if("2".equals(msgType)){
						PictureInfo pictureInfo = pictureInfoMongo.findPictureInfo(temp.getContent());
						if(pictureInfo!=null){
							temp.setWidth(pictureInfo.getWidth());
							temp.setHeight(pictureInfo.getHeight());
						}
					}
				}
			}
			
			packet.setTo(user_id);
			String txt = JSON.toJSONString(msgs);
			GroupMsgPacket reply = ServerPacketFactory.replyAddGroupMessage(user_id, txt );
			if (packet.getCmd()==PrivateMsgPacket.CMD_MSG_LIST) {
				reply.setCmd(GroupMsgPacket.NOTIFY_MSG_LIST);
			}else {
				reply.setCmd(GroupMsgPacket.NOTIFY_MSG_LIST_GMSG);
			}
			reply.setNotifyType(GroupMsgPacket.NT_RE_MSG_OK);
			clientConn.deliver(reply);
		}catch(Exception e){
			log.error("获取聊天列表信息出错", e);
			sendSystemPacket(clientConn, packet.getFrom(),e.getMessage(),GroupMsgPacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PRO_ERROR);
		}finally{
			DBManager.closeBindConnection(DBManager.getDefaultDataSourceName(Boolean.TRUE.booleanValue()));
		}
	}
	

	/**
	 * 获取群聊天人员列表
	 * @param clientConn
	 * @param packet
	 */
	public void listShareUser(ClientConnection clientConn, GroupMsgPacket packet) {
		try {
			GroupMsg groupMsg = packet.decoder(GroupMsg.class);
			//验证登陆输入的参数
			Map<String, Object> errerInfos = new HashMap<String, Object>();
			if(groupMsg.getUserId()==null){
				errerInfos.put("userId", "登陆者不能为空");
			}
			if(groupMsg.getShareid()==null){
				errerInfos.put("shareid", "共享信息类型不能为空");
			}
			Share share = shareDao.findShareByid(groupMsg.getShareid());
			User share_user = userDao.findUserByid(share.getUser_id());
			List<User> listUser = getShareUser(groupMsg, share_user, groupMsg.getUserId());
			if(!share_user.getId().equals( groupMsg.getUserId() ) ){
				User tempuser = new User();
				tempuser.setId(share_user.getId());
				tempuser.setName(share_user.getName());
				tempuser.setHead_pic(share_user.getHead_pic());
				listUser.add(tempuser);
			}
			
			GroupMsgPacket reply = ServerPacketFactory.replyAddGroupMessage(groupMsg.getUserId(), JSON.toJSONString(listUser) );
			reply.setCmd(GroupMsgPacket.NOTIFY_MSG_LIST_SHARE_USER);
			reply.setNotifyType(GroupMsgPacket.NT_RE_MSG_OK);
			clientConn.deliver(reply);
		} catch (DaoException e) {
			e.printStackTrace();
		}finally{
			DBManager.closeBindConnection(DBManager.getDefaultDataSourceName(Boolean.TRUE.booleanValue()));
		}
	}

	/**
	 * 获取群聊天胶片（图片）列表
	 * @param fromConn
	 * @param packet
	 */
	public void listPicture(ClientConnection clientConn, GroupMsgPacket packet) {
		try {
			GroupMsg groupMsg = packet.decoder(GroupMsg.class);
			//验证登陆输入的参数
			Map<String, Object> errerInfos = new HashMap<String, Object>();
			if(groupMsg.getUserId()==null){
				errerInfos.put("userId", "登陆者不能为空");
			}
			if(groupMsg.getSourceType()==null){
				errerInfos.put("sourceType", "共享信息类型不能为空");
			}
			
			if(groupMsg.getShareid()==null){
				errerInfos.put("shareid", "shareid不能为空");
			}
			if (errerInfos.size() > 0 ) {				
				sendSystemPacket(clientConn, packet.getFrom(),errerInfos.toString(),GroupMsgPacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PARAM_NULL);
				return ;
			}
			String user_id = groupMsg.getUserId();
			
			User myuser = userDao.findUserByid(user_id);
			if(myuser==null){
				sendSystemPacket(clientConn, packet.getFrom(),"没有找到用户",GroupMsgPacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PARAM_NULL);
				return ;
			}
			groupMsg.setSwitchboard_id(myuser.getSwitchboard_id());
		
			
			Integer start = groupMsg.getPage();
			if(start==null){
				start = 0;
			}
			groupMsg.setPage(start);
			
			List<GroupMsg> reuslt = groupMsgMongoDao.findGroupMsgByImgSlice(groupMsg);
			GroupMsgPacket reply = ServerPacketFactory.replyAddGroupMessage(user_id, JSON.toJSONString(reuslt) );
			reply.setCmd(GroupMsgPacket.NOTIFY_MSG_LIST_PICTURE);
			reply.setNotifyType(GroupMsgPacket.NT_RE_MSG_OK);
			clientConn.deliver(reply);
		} catch (DaoException e) {
			e.printStackTrace();
		} finally{
			DBManager.closeBindConnection(DBManager.getDefaultDataSourceName(Boolean.TRUE.booleanValue()));
		}
	}
	
	/**
	 * 查询最后的聊天记录
	 * @param clientConn
	 * @param packet
	 * @author wxy 2015年6月9日星期二中国标准时间下午2:53:21
	 */
	public void listLastMsg(ClientConnection clientConn, GroupMsgPacket packet) {
		try {
			GroupMsg groupMsg = packet.decoder(GroupMsg.class);
			//验证登陆输入的参数
			Map<String, Object> errerInfos = new HashMap<String, Object>();
			if(groupMsg.getUserId()==null){
				errerInfos.put("userId", "登陆者不能为空");
			}
			if (errerInfos.size() > 0 ) {				
				sendSystemPacket(clientConn, packet.getFrom(),errerInfos.toString(),GroupMsgPacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PARAM_NULL);
				return ;
			}
			String user_id = groupMsg.getUserId();
			
			User myuser = userDao.findUserByid(user_id);
			if(myuser==null){
				sendSystemPacket(clientConn, packet.getFrom(),"没有找到用户",GroupMsgPacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PARAM_NULL);
				return ;
			}
			String switchboard_id = myuser.getSwitchboard_id();
			groupMsg.setSwitchboard_id(switchboard_id);
			String[] groupByColumns = { "shareid" };
			List<GroupMsg> reuslt = groupMsgMongoDao.findGroupMsgByGroup(groupMsg,groupByColumns);
			ComparatorRelation comparator=new ComparatorRelation("created_at",Constant.ORDER_DESCENDING);
			if (reuslt!=null&&reuslt.size()>20) {
				reuslt = reuslt.subList(0, 20);
			}
			Collections.sort(reuslt, comparator);
			
			List<GroupMsg> reuslt_t = new ArrayList<GroupMsg>();
			GroupMsg gms = null;
			String msgType = "1";
			for (GroupMsg gm : reuslt) {
				try {
					gm.setSwitchboard_id(switchboard_id);
					gms = groupMsgMongoDao.readByCondition(gm);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (gms!=null) {
					Share share = shareDao.findShareByid(gms.getShareid());
					if(share!=null){
						if(!StringUtils.isBlank(gms.getMsgType())){
							msgType = gms.getMsgType();
						}else {
							msgType = "1";
						}
						gms.setGroup_avatar(share.getHead_pic());
						//如果共享信息类型是指数
						if(Constant.SHARE_TYPE_ITEM==gms.getSourceType()){
							//设置指数的原始ID
							String text_itemString = null;
							Item item = itemDao.findItemByid(gms.getSourceId());
							if(Constant.DATA_SOURCE_SHARE.equals(item.getData_source())){
								Item original_item = itemDao.findItemByid(item.getOriginal_item_id());
								gms.setSourceName(original_item.getItem_name());
								text_itemString = original_item.getAttrs();
							}else{
								gms.setSourceName(item.getItem_name());
								text_itemString = item.getAttrs();
							}
							
							if(!StringUtils.isBlank(text_itemString)){
								try {
									ItemAttrs itemAttrs = JSON.parseObject(text_itemString, ItemAttrs.class);
									groupMsg.setTextItem(itemAttrs.isTextItem());
								} catch (Exception e) {
								}
							}
							
						}else if(Constant.SHARE_TYPE_TEMPLATE==gms.getSourceType()){
							gms.setSourceName(share.getName());
						}
						//changeContent(gms);
						reuslt_t.add(gms);
					}
				}
			}
			
			GroupMsgPacket reply = ServerPacketFactory.replyAddGroupMessage(user_id, JSON.toJSONString(reuslt_t));
			reply.setCmd(GroupMsgPacket.NOTIFY_MSG_LIST_LASTMSG);
			reply.setNotifyType(GroupMsgPacket.NT_RE_MSG_OK);
			clientConn.deliver(reply);
		} catch (DaoException e) {
			e.printStackTrace();
		} finally{
			DBManager.closeBindConnection(DBManager.getDefaultDataSourceName(Boolean.TRUE.booleanValue()));
		}
	}
	
}
